package com.biz.primus.ms.oms.service.channel;

import com.biz.primus.base.exception.BizSilentException;
import com.biz.primus.common.utils.Copier;
import com.biz.primus.model.oms.vo.OmsChannelVo;
import com.biz.primus.ms.base.service.AbstractBaseService;
import com.biz.primus.ms.oms.dao.po.OmsChannel;
import com.biz.primus.ms.oms.dao.repository.ChannelRepository;
import com.biz.primus.model.oms.exception.OmsExceptions;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author yanweijin
 * @date 2017/11/3
 */
@Service
public class ChannelService extends AbstractBaseService{


	@Autowired
	private ChannelRepository channelRepository;

	private static final OmsChannelVo EMPTY_CHANNEL = new OmsChannelVo();

	private Cache<String, OmsChannelVo> cache = CacheBuilder.newBuilder()
			.expireAfterWrite(1, TimeUnit.MINUTES).maximumSize(1000).build(new CacheLoader<String, OmsChannelVo>() {
		@Override
		public OmsChannelVo load(String key) throws Exception {
			OmsChannel po = channelRepository.findByChannel(key);
			if(po!=null){
				return Copier.from(po).to(new OmsChannelVo());
			}
			return EMPTY_CHANNEL;
		}
	});

	/**
	 * 新增一个渠道
	 * @param vo
	 */
	public void saveChannel(OmsChannelVo vo){
		OmsChannel channel = Copier.from(vo).to(new OmsChannel());
	}

	/**
	 * 查询并验证一个渠道
	 * @param channel
	 * @param token
	 * @return true:验证通过/false:没有这个渠道或验证失败
	 */
	public boolean queryChannel(String channel, String token){

		return true;
	}


	/**
	 * 根据渠道编号查询渠道vo,如果
	 * @param channel
	 * @return
	 */
	public OmsChannelVo findChannelByCode(String channel){
		OmsChannelVo vo = cache.getIfPresent(channel);
		if(vo==EMPTY_CHANNEL){
			throw new BizSilentException(OmsExceptions.CHANNEL_ERROR);
		}
		return vo;
	}





}
